package cn.icanci.loopstack.rec.admin.web.controller.register;

import cn.icanci.loopstack.rec.admin.biz.service.RegisterService;
import cn.icanci.loopstack.rec.admin.web.form.PublishForm;
import cn.icanci.loopstack.rec.admin.web.form.RegisterQueryForm;
import cn.icanci.loopstack.rec.common.model.config.RegisterVO;
import cn.icanci.loopstack.rec.common.model.socket.RegisterDTO;
import cn.icanci.loopstack.rec.common.result.R;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 基于域发布更新
 * 
 * @author icanci
 * @since 1.0 Created in 2022/11/20 19:53
 */
@RestController
@RequestMapping("/rec/register")
public class RegisterController {

    @Resource
    private RegisterService registerService;

    @PostMapping("query")
    public R query(@RequestBody RegisterQueryForm form) {
        return R.builderOk().data("queryPage", registerService.queryPage(form.getRegister(), form.getPaginator().getCurrentPage(), form.getPaginator().getPageSize())).build();
    }

    @PostMapping("publish")
    public R debug(@RequestBody PublishForm publish) {
        registerService.publish(publish.getUuid(), publish.getDomainCode());
        return R.builderOk().build();
    }

    /**
     * TODO SDK注册的时候需要返回注册的结果
     *      要识别注册的结果，然后SDK做响应的操作
     *      也就是当全部域都发生注册的时候，就不再自动注册
     * @param register register
     * @return 返回注册的结果
     */
    @PostMapping("doRegister")
    public R register(@RequestBody RegisterDTO register) {
        doRegister(register);
        return R.builderOk().data("register", register).build();
    }

    /**
     * 构建注册请求
     * 
     * @param register register
     * @return 返回注册请求数据
     */
    private void doRegister(RegisterDTO register) {
        String domainCode = register.getDomain();
        if (StringUtils.isBlank(domainCode)) {
            return;
        }
        Set<String> domains = Sets.newHashSet(domainCode.replaceAll("\\s*", StringUtils.EMPTY).split(","));
        List<RegisterVO> registers = Lists.newArrayList();
        for (String domain : domains) {
            RegisterVO registerVO = new RegisterVO();
            registerVO.setClientAddress(register.getClientAddress());
            registerVO.setClientPort(register.getClientPort());
            registerVO.setAppName(register.getAppName());
            registerVO.setRegisterTime(new Date());
            registerVO.setLastUpdateTime(new Date());
            registerVO.setDomain(domain);
            registers.add(registerVO);
        }
        registerService.doRegister(registers);
    }
}
